package com.zf.shuashua.advert;

import android.app.Activity;

import com.qq.e.ads.rewardvideo.RewardVideoAD;
import com.qq.e.ads.rewardvideo.RewardVideoADListener;
import com.qq.e.comm.util.AdError;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.AdvertUtils;
import com.zf.shuashua.bean.AdvertReport;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.manager.ActionThirdReportManager;
import com.zf.shuashua.utils.Util;

import java.lang.ref.WeakReference;

/**
 * 激励视频展示
 * 腾讯优量汇激励视频
 */
public class RewardAdvertTencentManager implements RewardVideoADListener {

    private String mAdvertType = AdvertConstants.REWARD_TYPE_TASK;
    private RewardVideoAD rewardVideoAD;
    private WeakReference<Activity> weakReference;
    private static RewardAdvertTencentManager instance;
    private String mCodeId = "7011947427907880";
    private String mReportID = "";

    private OnRewardListener mListener;

    private String uuiThirdAdvert;
    private String planId;
    private boolean isComplete = false;

    private RewardAdvertTencentManager() {
    }

    public static RewardAdvertTencentManager getInstance() {
        if (null == instance) {
            synchronized (RewardAdvertTencentManager.class) {
                if (null == instance) {
                    instance = new RewardAdvertTencentManager();
                }
            }
        }
        return instance;
    }

    /**
     * 补量用
     * @param activity
     * @param advertType
     * @param listener
     */
    public void showAdvert(Activity activity, String advertType, String reportId, OnRewardListener listener) {
        this.weakReference = new WeakReference<>(activity);
        this.mAdvertType = advertType;
        this.mReportID = reportId;
        this.mListener = listener;
        isComplete = false;
        mCodeId = getCodeId();
        showByteAdvert();
    }

    /**
     * 根据配置项获取
     * @param activity
     * @param advertType
     * @param codeId
     * @param listener
     */
    public void showAdvert(Activity activity, String advertType, String reportId, String codeId, OnRewardListener listener) {
        this.weakReference = new WeakReference<>(activity);
        this.mAdvertType = advertType;
        this.mReportID = reportId;
        this.mListener = listener;
        isComplete = false;
        mCodeId = codeId;
        showByteAdvert();
    }

    /**
     * 优量汇广告
     */
    private void showByteAdvert() {
        uuiThirdAdvert = Util.getUUID32();
        rewardVideoAD = new RewardVideoAD(weakReference.get(), mCodeId, this);
        planId = System.identityHashCode(rewardVideoAD) + "";
        rewardVideoAD.loadAD();
        reportRequestStart();
    }

    private void reportRequestStart(){
        ActionThirdReportManager.getInstance().reportRequestStart(2, 2, mCodeId, 1);
    }

    private void reportRequestSucc(int return_num) {
        ActionThirdReportManager.getInstance().reportRequestSucc(2, 2, mCodeId, return_num);
    }

    private void reportRequestFail(String error_code, String error_msg){
        ActionThirdReportManager.getInstance().reportRequestFail(2, 2, mCodeId, 1, error_code, error_msg);
    }

    private void reportRequestRend(String error_code, String error_msg){
        ActionThirdReportManager.getInstance().reportRequestRend(2, 2, mCodeId, error_code, error_msg);
    }

    /**
     * 广告加载成功，可在此回调后进行广告展示
     **/
    @Override
    public void onADLoad() {
        if(rewardVideoAD != null && !rewardVideoAD.hasShown()){
            rewardVideoAD.showAD();
        }
        reportRequestSucc(1);
//        String msg = "load ad success ! expireTime = " + new Date(System.currentTimeMillis() +
//                rewardVideoAD.getExpireTimestamp() - SystemClock.elapsedRealtime());
//        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
//        Log.d(TAG, "eCPMLevel = " + rewardVideoAD.getECPMLevel());
    }

    /**
     * 视频素材缓存成功，可在此回调后进行广告展示
     */
    @Override
    public void onVideoCached() {
//        Log.i(TAG, "onVideoCached");
    }

    /**
     * 激励视频广告页面展示
     */
    @Override
    public void onADShow() {
//        Log.i(TAG, "onADShow");
        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.VideoStart, getReportType(), "2");
    }

    /**
     * 激励视频广告曝光
     */
    @Override
    public void onADExpose() {
//        Log.i(TAG, "onADExpose");
    }

    /**
     * 激励视频触发激励（观看视频大于一定时长或者视频播放完毕）
     */
    @Override
    public void onReward() {
//        Log.i(TAG, "onReward");
//        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.VideoEnd, getReportType(), "2");
        isComplete = true;
    }

    /**
     * 激励视频广告被点击
     */
    @Override
    public void onADClick() {
//        Map<String, String> map = rewardVideoAD.getExts();
//        String clickUrl = map.get("clickUrl");
//        Log.i(TAG, "onADClick clickUrl: " + clickUrl);
        if (mListener != null) {
            mListener.onAdClick();
        }
        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.VideoClick, getReportType(), "2");
    }

    /**
     * 激励视频播放完毕
     */
    @Override
    public void onVideoComplete() {
//        Log.i(TAG, "onVideoComplete");
        if (mListener != null) {
            mListener.onVideoComplete();
        }
//        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.VideoEnd, getReportType(), "2");
    }

    /**
     * 激励视频广告被关闭
     */
    @Override
    public void onADClose() {
//        Log.i(TAG, "onADClose");
        dealClose(mListener);
    }

    private void dealClose(OnRewardListener listener){
        if(!isComplete){
            return;
        }
        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.VideoEnd, getReportType(), "2", new ACallback<BaseData>() {
            @Override
            public void onSuccess(BaseData data) {
                if (data != null && data.isStatus()) {
                    weakReference.get().runOnUiThread(() -> {
                        if (listener != null) {
                            listener.onAdClose();
                        }
                    });
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {

            }
        });
    }

    /**
     * 广告流程出错
     */
    @Override
    public void onError(AdError adError) {
        weakReference.get().runOnUiThread(() -> {
            if (mListener != null) {
                mListener.onVideoError();
            }
        });
        if(adError != null){
            reportRequestFail(adError.getErrorCode() + "", adError.getErrorMsg());
        }
    }

    private String getReportType() {
        return AdvertUtils.getReportType(mAdvertType, mReportID);
    }

    private String getCodeId() {
        return AdvertUtils.getTencentCodeId(mAdvertType);
    }

}
